package com.dy.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.dy.common.R;
import com.dy.entity.Employee;
import com.dy.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName:EmployeeFilter
 * Package:com.dy.filter
 * Description:  后台员工管理平台登录拦截器
 *
 * @Date:2022/8/3 19:12
 * @Author:dy
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class EmployeeLoginFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //定义不被过滤的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //检查本次请求是否需要放行
        boolean check = checkOut(urls,request.getRequestURI());
        //true 不需要过滤
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        Long empId = (Long) request.getSession().getAttribute("employee");
        //1.1 过滤 判断是否已登录
        if(empId != null){
            //员工已登录， 将员工ID 存入线程内存
            CurrentHolder.setCurrent(empId);
            filterChain.doFilter(request,response);
            return;
        }

        Long userId = (Long) request.getSession().getAttribute("user");

        //1.2 过滤 判断是否已登录
        if(userId != null){
            //用户已登录， 将用户ID 存入线程内存
            CurrentHolder.setCurrent(userId);
            filterChain.doFilter(request,response);
            return;
        }
        // 返回响应
        response.getWriter().write(JSONUtil.toJsonStr(R.error("NOTLOGIN")));
        return;
    }
    /**
     * @Author dy
     * @Description:  检查本次请求是否需要放行
     * * @return boolean
     */
    private boolean checkOut(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }

}
